#!/bin/bash

echo "🚀 启动 NestJS 应用 (PM2)"

# 检查是否已构建
if [ ! -d "dist" ]; then
    echo "📦 构建项目..."
    npm run build
fi

# 检查PM2是否已安装
if ! command -v pm2 &> /dev/null; then
    echo "❌ PM2 未安装，正在安装..."
    npm install -g pm2
fi

# 停止现有进程（如果存在）
echo "🛑 停止现有进程..."
pm2 stop text-tags-backend 2>/dev/null || true
pm2 delete text-tags-backend 2>/dev/null || true

# 启动应用
echo "🔄 启动应用..."
pm2 start ecosystem.config.js --env production

# 保存PM2配置
pm2 save

# 设置开机自启（可选）
echo "⚙️  设置开机自启..."
pm2 startup 2>/dev/null || echo "⚠️  需要手动运行: sudo env PATH=\$PATH:/usr/bin /usr/lib/node_modules/pm2/bin/pm2 startup systemd -u \$USER --hp \$HOME"

echo "✅ 应用已启动！"
echo ""
echo "📋 常用命令:"
echo "   pm2 status          - 查看状态"
echo "   pm2 logs            - 查看日志"
echo "   pm2 restart all     - 重启所有应用"
echo "   pm2 stop all        - 停止所有应用"
echo "   pm2 monit           - 监控面板"
echo ""
echo "🌐 应用地址: http://localhost:3000/api"
